package com.java.netty.client.pptp;

import com.alibaba.fastjson.JSONObject;
import com.java.netty.common.codec.PptpDecoder;
import com.java.netty.common.codec.PptpEncoder;
import com.java.netty.common.device.DeviceEnvInfo;
import com.java.netty.common.device.DeviceExtInfo;
import com.java.netty.common.device.DeviceInfo;
import com.java.netty.common.enums.MsgType;
import com.java.netty.common.enums.ProtocolVer;
import com.java.netty.common.helper.PPTPHelper;
import com.java.netty.common.helper.PptpJsonDataHelper;
import com.java.netty.common.pptp.Pptp;
import com.java.netty.common.pptp.PptpHead;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.nio.charset.StandardCharsets;

public class StartClient {
    final static String host = "127.0.0.1";
   final static int port = 50030;


    public static void main(String[] args) throws Exception {
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            bootstrap
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline()
                                    //如果去掉LengthFieldBasedFrameDecoder，LengthFieldPrepender 就能正确拿到消息版本，消息类型，和待命时间
//                                    .addLast(new LengthFieldBasedFrameDecoder(ByteOrder.LITTLE_ENDIAN, 1024, 0, 4, 0, 0, true))
//                                    .addLast(new LengthFieldPrepender(ByteOrder.LITTLE_ENDIAN, 4, 0, false))
                                    .addLast(new PptpDecoder())
                                    .addLast(new PptpEncoder())
                                    .addLast(new LoggingHandler(LogLevel.INFO))
                                    .addLast(new ClientHandler());
                        }
                    });
            Pptp rPptp = new Pptp();
            String deviceName = "sum-523sn";
            String clientId = "234234";
            DeviceEnvInfo deviceEnvInfo = new DeviceEnvInfo();
            deviceEnvInfo.setDeviceCode("fdsafasff");
            deviceEnvInfo.setDeviceSn("1111111111");
            deviceEnvInfo.setDeviceType("2344");
            DeviceExtInfo deviceExtInfo = new DeviceExtInfo();
            deviceExtInfo.setActiveId("4234");
            deviceExtInfo.setBrand("23442");
            deviceExtInfo.setAndroidVer("432.0");
            deviceExtInfo.setDeviceChp("4234");
            deviceExtInfo.setDeviceMod("4234");
            deviceExtInfo.setDeviceVer("62002042");
            deviceExtInfo.setOpenId("423");
            deviceExtInfo.setEmcId("2342342342");
            deviceEnvInfo.setDeviceCode("4234");
            deviceExtInfo.setTxId("ab234523452345c34");
            deviceExtInfo.setPushVer("423");
            deviceExtInfo.setDeviceTcVer("423");
            DeviceInfo deviceInfo = new DeviceInfo(deviceName, clientId, deviceEnvInfo, deviceExtInfo);
            JSONObject dataJson = PptpJsonDataHelper.getEnvAJsonData(deviceInfo);
            //消息类型为7，消息版本3，待命时间为100, datajson为消息体
            PptpHead pmtpHead = new PptpHead(MsgType.PPTP_CMD_ENV_Q.getType(), ProtocolVer.PPTP_V3.getVersion(),
                    2, dataJson.toString().length());
            rPptp.setHead(pmtpHead);
            rPptp.setData(dataJson.toString());
            System.out.println("往端口：" + port + "开始发送消息");
           int length = dataJson.toString().length();
           System.out.println(length);
            //组装消息
            byte[] msg = PPTPHelper.buildMsg(rPptp);
            ChannelFuture cf = bootstrap.connect(host, port).sync();
           for (int i = 0; i < 5; i++) {
                System.out.println("第" + i + "次发送消息");
                System.out.println(rPptp.toString());
                cf.channel().writeAndFlush(Unpooled.copiedBuffer(msg));
              BufferedWriter out = new BufferedWriter(new FileWriter("msg.txt"));
              String s = new String(msg, StandardCharsets.UTF_8);
              out.write(s);
              out.close();
              System.out.println("文件创建成功！");

              //                File file = new File();
              //                file.
                //cf.channel().writeAndFlush(msg);
                System.out.println("----包长度为：" + msg.length);
                //cf.channel().writeAndFlush(msg);
            }
            System.out.println("往端口：" + port + "发送完成");
            cf.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
            System.out.println("客户端己释放");
        }
    }
}
